<?php
namespace App\WebSocket\Controller;

use App\Storage\OnlineUser;
use App\Storage\ServiceRoleRedis;
use App\WebSocket\Actions\User\UserInfo;
use App\WebSocket\Actions\User\UserOnline;

class Index extends Base {

    /**
     * 当前用户信息
     */
    function info() {
        $info = $this->currentUser();
        if ($info) {
            $message = new UserInfo;
            $message -> setIntro('个人介绍');
            $message -> setAvatar($info['avatar']);
            $message -> setUserFd($info['fd']);
            $message -> setUsername($info['username']);
            $this->response()->setMessage($message);
        }
    }

    /**
     * 在线用户列表
     */
    function online() {
        $table = OnlineUser::getInstance()->table();
        $users = array();

        $client = $this->caller()->getClient();
        $params = $this->caller()->getArgs();

        $isShop = isset($params['isShop']) && in_array(intval([$params['isShop']]),[1,2]) ? intval($params['isShop']) : 0;
        if ($isShop == 0) {
            // 仅展示用户一个人
            $user = OnlineUser::getInstance()->get($client->getFd());
            $users['user' . $user['fd']] = $user;
//            $users[] = $user;
        }

        if ($isShop == 1) {
            // 展示所有的归属于这个shop的用户
            $shopId = $params['shopId'];
            foreach ($table as $user) {
                if ($shopId && intval($shopId) > 0 && intval($shopId) == $user['shop_id']) { // 存在shop_id，按shop_id进行房间分类
                    $users['user' . $user['fd']] = $user;
//                    $users[] = $user;
                }
            }
            // 过滤商户
            $serverInfo = ServiceRoleRedis::getInstance($shopId)->get($shopId);
            if (isset($serverInfo) && !empty($serverInfo)) {
                $serUser = array_column($serverInfo,'shop_user_id');
                if (isset($serUser) && !empty($serUser)) {
                    foreach ($users as $k => $user) {
                        if (in_array($user['user_id'],$serUser)) {
                            unset($users[$k]);
                        }
                    }
                }
            }
        }

        if (!empty($users)) {
            $message = new UserOnline();
            $message->setList($users);
            $this->response()->setMessage($message);
        }
    }

    function heartbeat() {
        $this->response()->setMessage('PONG');
    }

}